<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 也可以在 <style> 中 import
import { computed, onBeforeUnmount, watch, ref, onMounted } from 'vue'
import {
  Editor,
  Toolbar,
  getEditor,
  removeEditor,
} from '@wangeditor/editor-for-vue'

import {
  IDomEditor, // 编辑器实例接口
  IEditorConfig, // 编辑器配置
  IToolbarConfig, // 工具栏配置
  SlateTransforms,
} from '@wangeditor/editor'
import { AlertType } from '@wangeditor/core/dist/core/src/config/interface'
import { cloneDeep } from 'lodash'
import { postData } from '@/api/axios'
type Callback = (type: boolean) => void
type InsertFnType = (url: string, alt: string, href: string) => void
const editorId = `w-e-${Math.random().toString().slice(-5)}`

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      fieldName: 'file',
      server: '/api/upload',

      // 自定义上传
      async customUpload(file: any, insertFn: InsertFnType) {
        // files 即选中的文件
        console.log(file, 'files')
        let param = new FormData() // 创建form对象
        param.append('file', file) // 通过append向form对象添加数据
        let config = {
          headers: { 'Content-Type': 'multipart/form-data' },
        }
        // 自己实现上传，并得到图片 url alt href
        let res: any = await postData('/upload', param, config)
        // 最后插入图片
        insertFn(res.url, '', '')
      },
    },
    insertImage: {
      checkImage(src: string) {
        console.log('image src', src)
        if (src.indexOf('http') !== 0) {
          return '图片网址必须以 http/https 开头'
        }
        return true
      },
    },
  },
}

const emit = defineEmits(['changeEditor'])
/**
 * 给editor赋值的方法
 */

let defaultHtml = ref('')

const setDefaultContent = (content: any) => {
  const editor: any = getEditor(editorId)
  editor.dangerouslyInsertHtml(content)
}

const contentChagne = (editor: any) => {
  emit('changeEditor', editor.getHtml())
}
// 及时销毁编辑器
onBeforeUnmount(() => {
  const editor = getEditor(editorId)
  if (editor == null) return
  // 销毁，并移除 editor
  editor.destroy()
  removeEditor(editorId)
})

// 重点！！这里需要使用defineExpose暴露出去
defineExpose({
  setDefaultContent,
})
</script>
<template>
  <div class="article_page">
    <!-- 工具栏 -->
    <Toolbar
      :editorId="editorId"
      mode="default"
      style="border-bottom: 1px solid #ccc"
    />
    <!-- 编辑器 -->
    <Editor
      :editorId="editorId"
      :defaultConfig="editorConfig"
      :defaultHtml="defaultHtml"
      @onChange="contentChagne"
      mode="default"
      style="height: 500px; overflow-y: hidden"
    />
  </div>
</template>

<style lang="scss" scoped>
.article_page {
  border: 1px solid #ccc;
}
</style>
